#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CronPy Windows服务诊断脚本 (Python版本)
"""

import os
import sys
import importlib.util

def check_python_environment():
    """检查Python环境"""
    print("[1/6] 检查Python环境...")
    try:
        print(f"Python版本: {sys.version}")
        print("✓ Python环境正常")
        return True
    except Exception as e:
        print(f"✗ Python环境异常: {e}")
        return False

def check_project_structure():
    """检查项目结构"""
    print("\n[2/6] 检查项目结构...")

    project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    files_to_check = [
        os.path.join(project_root, 'config', 'scheduler.yaml'),
        os.path.join(project_root, 'config', 'tasks.json'),
        os.path.join(project_root, 'scheduler', 'windows_service.py')
    ]

    file_names = [
        'config/scheduler.yaml',
        'config/tasks.json',
        'scheduler/windows_service.py'
    ]

    all_exist = True
    for file_path, file_name in zip(files_to_check, file_names):
        if os.path.exists(file_path):
            print(f"✓ {file_name} 存在")
        else:
            print(f"✗ {file_name} 不存在")
            all_exist = False

    return all_exist

def check_dependencies():
    """检查Python依赖"""
    print("\n[3/6] 检查Python依赖...")

    try:
        import win32service
        print("✓ pywin32库正常")
        return True
    except ImportError:
        print("✗ pywin32未安装")
        print("请运行: pip install pywin32")
        return False

def test_config_loading():
    """测试配置加载"""
    print("\n[4/6] 测试配置加载...")

    try:
        # 添加路径
        project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        sys.path.insert(0, project_root)
        sys.path.insert(0, os.path.join(project_root, 'scheduler'))

        from scheduler.config_manager import ConfigManager
        config_manager = ConfigManager('config')
        config = config_manager.get_scheduler_config()

        print("✓ 配置加载成功")
        print(f"  - max_workers: {config.get('max_workers', 'N/A')}")
        print(f"  - log_file: {config.get('log_file', 'N/A')}")

        return True
    except Exception as e:
        print(f"✗ 配置加载失败: {e}")
        return False

def test_scheduler_creation():
    """测试调度器创建"""
    print("\n[5/6] 测试调度器创建...")

    try:
        # 添加路径
        project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        sys.path.insert(0, project_root)
        sys.path.insert(0, os.path.join(project_root, 'scheduler'))

        from scheduler.task_scheduler import TaskScheduler
        scheduler = TaskScheduler(max_workers=1, log_file='scheduler.log')
        print("✓ 调度器创建成功")
        return True
    except Exception as e:
        print(f"✗ 调度器创建失败: {e}")
        return False

def check_service_status():
    """检查服务状态"""
    print("\n[6/6] 检查服务状态...")

    try:
        # 添加路径
        project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        sys.path.insert(0, project_root)
        sys.path.insert(0, os.path.join(project_root, 'scheduler'))

        from scheduler.windows_service import ServiceManager
        service_manager = ServiceManager()
        status = service_manager.get_service_status()

        if status is not None:
            print("✓ 服务状态检查完成")
        else:
            print("⚠ 服务可能未安装")
        return True
    except Exception as e:
        print(f"⚠ 服务状态检查失败: {e}")
        return False

def main():
    """主函数"""
    print("=" * 40)
    print("CronPy Windows服务诊断脚本 (Python版本)")
    print("=" * 40)
    print()

    # 执行所有检查
    checks = [
        check_python_environment,
        check_project_structure,
        check_dependencies,
        test_config_loading,
        test_scheduler_creation,
        check_service_status
    ]

    results = []
    for check_func in checks:
        try:
            result = check_func()
            results.append(result)
        except Exception as e:
            print(f"检查过程中出错: {e}")
            results.append(False)

    print("\n" + "=" * 40)
    print("诊断完成！")
    print("=" * 40)

    # 总结结果
    passed = sum(results)
    total = len(results)

    print(f"\n检查结果: {passed}/{total} 通过")

    if passed == total:
        print("✓ 所有检查都通过了！")
    else:
        print("⚠ 发现了一些问题，请根据上述输出进行修复。")

    print("\n如需进一步帮助，请查看 scheduler.log 文件。")

    return passed == total

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
